<!--
 * @author guojiteng
 闯关策略模板列表
 -->
<template>
  <section class="a-rush-template-list">
    <el-collapse-transition>
      <div v-show="searchshow" class="main-search merge">
        <span class="svg-container">
          <svg-icon icon-class="search" />
        </span>
        <el-input v-model.trim="listQuery.name" placeholder="请输入关口名称搜索" class="search-input" />
        <div class="search-btn">
          <el-button class="filter-item" type="primary" @click="handleFilter">搜索</el-button>
          <el-button class="filter-item" type="primary" @click="handleReset">重置</el-button>
        </div>
      </div>
    </el-collapse-transition>
    <section class="main-buttons">
      <section class="main-buttons-title">
        <span>关口列表</span>
      </section>
      <section class="main-buttons-btns">
        <!--        <el-button-->
        <!--            type="primary"-->
        <!--            class="filter-item"-->
        <!--            style="margin-left: 10px;"-->
        <!--            @click="handleImport"-->
        <!--        >导入-->
        <!--        </el-button>-->
        <el-button
          v-if="ctType !=2"
          type="primary"
          class="filter-item"
          style="margin-left: 10px;"
          @click="handleGenerate"
        >一键生成
        </el-button>
        <el-button

          v-if="ctType !=2"
          type="primary"
          class="filter-item"
          style="margin-left: 10px;"
          @click="handleCreate"
        >新建
        </el-button>
        <el-button
          class="filter-item"
          style="margin-left: 10px;"
          @click="handleBack"
        >返回
        </el-button>
      </section>
    </section>
    <section class="main-table">
      <v-table :list="list" tag="rushPass" :list-loading="listLoading" :filter-column="filtercolumn" :selection="false">
        <el-table-column label="操作" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button
              v-if="ctType !=2"
              type="text"
              size="mini"
              @click="handleEdit(scope.row)"
            >编辑</el-button>
            <el-button v-if="scope.row.id===list[list.length-1].id&&ctType !=2" type="text" size="mini" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </v-table>
    </section>
    <!--导入-->
    <el-dialog v-el-drag-dialog :close-on-click-modal="false" :visible.sync="dialogUploadVisible" title="导入关口" center width="500px" @close="handleClosed">
      <el-upload
        ref="upload"
        v-loading="loadingUpload"
        element-loading-text="正在上传请稍后"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        :auto-upload="false"
        :on-success="uploadSuccess"
        :on-error="uploadError"
        :action="uploadaction"
        :headers="uploadHeaders"
        :data="uploadData"
        accept=".xls, .xlsx"
        class="upload-demo"
        drag
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div slot="tip" class="el-upload__tip" style="text-align: right">
          只能上传.xls,.xlsx
          <el-button type="text" @click="handleDownload">下载模板</el-button>
        </div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button style="padding: 8px 30px;" type="primary" @click="handleClosed">取消</el-button>
        <el-button style="padding: 8px 30px;" type="primary" @click="submitUpload()">确认</el-button>
      </span>
    </el-dialog>
    <!-- 导入的错误信息  -->
    <el-dialog v-el-drag-dialog :close-on-click-modal="false" :visible.sync="dialogUploadErrorTextVisible" title="错误信息" center width="500px">
      <div class="error-text" style="height: 600px;overflow-y: auto">
        <el-row>
          <el-col v-for="(item, index) in uploadErrorList" :key="index" :span="24" style="margin-bottom: 10px;">{{ index + 1 }}、{{ item }}</el-col>
        </el-row>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button style="padding: 8px 30px;" type="primary" @click="dialogUploadErrorTextVisible = false">关闭</el-button>
        <el-button style="padding: 8px 30px;" type="primary" @click="copyErrorText()">复制</el-button>
      </span>
    </el-dialog>
  </section>
</template>
<script>
import VTable from '@/components/Table'
import Pagination from '@/components/Pagination'
import { queryList, queryListSaas } from '../api/templateList'
import elDragDialog from '@/directive/el-drag-dialog'
import { exportSign, importSign } from '@/utils/fileImportOrExportSign'
import { del } from '@/views/skill/answerRush/api/pass'
export default {
  name: 'PassList',
  components: { Pagination, VTable },
  directives: { elDragDialog },
  data() {
    return {
      id: '',
      searchshow: true,
      listQuery: {
        page: 1,
        limit: 10,
        name: ''
      },
      list: [],
      listLoading: false,
      dialogUploadVisible: false,
      loadingUpload: false,
      uploadData: {
        dataId: ''
      },
      uploadaction: '/API-ENTERPRISE-BACKEND/backend/rushPass/templateImport',
      uploadHeaders: { ttsxbwqm: '', ttsxsjzc: '', ttsxyhcs: '' },
      dialogUploadErrorTextVisible: false,
      uploadErrorList: [],
      ctType: 1
    }
  },
  created() {
    this.id = this.$route.query.i || ''
    if (this.$route.query.relevanceId) {
      this.ctType = 2
      this.id = this.$route.query.relevanceId
      console.log(this.ctType)
    }
    this.uploadData.dataId = this.id
    this.getList()
  },
  methods: {
    /**
     * 一键生成
     * */
    handleGenerate() {
      this.$router.push({ path: this.$filterPath('passManage'), query: { type: 'c', i: this.id, pt: 'g' }})
    },

    handleEdit(row) {
      this.$router.push({ path: this.$filterPath('passManage'), query: { type: 'u', ui: row.id }})
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该关口, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        return new Promise((resolve, reject) => {
          del(row.id).then(() => {
            loading.close()
            this.$message({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }).catch(error => {
            loading.close()
            reject(error)
          })
        })
      }).catch()
    },
    handleCreate() {
      this.$router.push({ path: this.$filterPath('passManage'), query: { type: 'c', i: this.id }})
    },
    /**
     * 复制错误消息
     */
    copyErrorText() {
      let val = ''
      this.uploadErrorList.forEach(item => {
        val += item + '\n'
      })
      const input = document.createElement('input')
      input.setAttribute('readonly', 'readonly')
      input.setAttribute('value', val)
      document.body.appendChild(input)
      input.select()
      if (document.execCommand('copy')) {
        document.execCommand('copy')
        this.$message({
          title: '成功',
          message: '复制成功！',
          type: 'success',
          duration: 1500
        })
      }
      document.body.removeChild(input)
    },
    submitUpload() {
      if (this.$refs['upload'].uploadFiles.length === 0) {
        this.$message.error('请上传文件')
      } else {
        this.loadingUpload = true
        this.uploadHeaders = importSign({}, { dataId: this.id })
        setTimeout(() => {
          this.$refs.upload.submit()
        }, 1000)
      }
    },
    handleDownload() {
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = '/API-ENTERPRISE-BACKEND/backend/rushPass/downloadPassTemplate' + exportSign({ type: '1' }).paramStr
      link.setAttribute('download', '关口模版.xlsx')
      link.setAttribute('target', '_blank')
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    handleImport() {
      this.dialogUploadVisible = true
    },
    handleUploadQues() {
      this.dialogUploadVisible = true
    },
    uploadSuccess(data) {
      this.loadingUpload = false
      if (data.code === '200') {
        this.$message({
          message: '导入成功',
          type: 'success'
        })
        this.dialogUploadVisible = false
        this.uploadQuesDialogVisible = false
        this.$refs.upload.clearFiles()
        this.getList()
      } else {
        this.$message.error(data.msg || '网络异常')
        if (data.data.fileid) {
          const link = document.createElement('a')
          link.style.display = 'none'
          link.href = '/API-ENTERPRISE-BACKEND/backend/rushPass/downloadCheckFile' + exportSign({ errorId: data.data.fileid }).paramStr
          link.setAttribute('download', '关口模版.xlsx')
          link.setAttribute('target', '_blank')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        }
        this.$refs.upload.clearFiles()
        if (data.data) {
          this.uploadErrorList = data.data
          this.dialogUploadErrorTextVisible = true
        }
      }
    },
    uploadError(err) {
      this.loadingUpload = false
      this.$message.error(err || '网络异常')
    },
    handleClosed() {
      this.dialogUploadVisible = false
      this.loadingUpload = false
      this.$refs.upload.clearFiles()
    },
    // 返回
    handleBack() {
      this.$router.back()
    },
    filtercolumn(scope, item) {
      return scope.row[item]
    },

    handleReset() {
      this.listQuery.page = 1
      this.listQuery.name = ''
      for (const i in this.search) {
        if (this.search['' + i + ''] instanceof Array) {
          this.search['' + i + ''] = []
        } else {
          this.search['' + i + ''] = ''
        }
      }
      this.getList()
    },

    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

    getList(obj) {
      this.listLoading = true
      var query = {
        page: obj ? obj.page : this.listQuery.page,
        pageSize: obj ? obj.limit : this.listQuery.limit,
        name: this.listQuery.name,
        dataId: this.id
      }
      return new Promise((resolve, reject) => {
        if (this.ctType == 2) {
          queryListSaas(query).then(response => {
            this.list = response.data.data
            this.listLoading = false
          }).catch(error => {
            reject(error)
            this.listLoading = false
          })
        } else {
          queryList(query).then(response => {
            this.list = response.data.data
            this.listLoading = false
          }).catch(error => {
            reject(error)
            this.listLoading = false
          })
        }
      })
    }
  }
}
</script>
<style lang="scss">
.a-rush-template-list {
  padding: 10px;
  .main-search {
    background-color: #fff;
    padding: 0 10px;
    .svg-container {
      padding: 0 5px 0 10px;
      color: #bfced6;
      vertical-align: middle;
      display: inline-block;
    }
    .search-input {
      width: 60%;
      position: relative;
      &:after {
        content: '';
        position: absolute;
        left: -25px;
        right: 0;
        bottom: 8px;
        height: 1px;
        background: rgba(226, 227, 232, 1);
      }
      input {
        outline: none;
        background: transparent;
        border: none;
        outline: medium;
        padding: 0;
        &:focus {
          outline: none;
          background-color: transparent;
        }
      }
    }
    .search-btn {
      display: inline-block;
      float: right;
      .el-button.is-round {
        padding: 10px 30px;
        margin-right: 34px;
      }
      .search-more {
        font-size: 14px;
        font-weight: 500;
        @include font-color($mainColor);
        cursor: pointer;
        margin-left: 10px;
      }
    }

    &.merge {
      height: 50px;
      line-height: 50px;
    }

    &.separate {
      .search-inner {
        padding-top: 10px;
        .search-inner-item {
          .item-label {
            height: 30px;
            line-height: 30px;
            font-size: 14px;
            color: #a6a6a6;
            font-weight: 400;
          }
          .el-input {
            position: relative;
            &.el-date-editor input {
              padding-left: 30px;
            }
            .el-input__inner {
              border: none;
              padding: 0;
            }
            &:after {
              content: '';
              height: 1px;
              background-color: #e2e3e8;
              position: absolute;
              left: 0;
              right: 0;
              bottom: 0;
            }
          }
        }
      }
      .search-btn {
        text-align: center;
        display: block;
        float: none;
        height: 56px;
        line-height: 56px;
      }
    }
  }

  .main-buttons {
    display: flex;
    line-height: 36px;
    margin-top: 10px;
    .main-buttons-title {
      flex: 1;
      height: 36px;
      line-height: 36px;
      font-size: 16px;
      font-weight: bold;
      color: rgba(51, 51, 51, 1);
    }
  }
  .upload-demo{
    .el-upload-dragger{
      width: 100%;
    }
    display: flex;
    flex-direction: column;
    justify-content: center;
  }
}
</style>
